package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.vo.JsonResult;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.HourlyActivityAnalysisMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.ErrorUtil;
import edu.sdbi.judge.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Order(15)
@Service
public class Judge_15 implements GetJudgeIpResultService {
    @Autowired
    private HttpUtil httpUtil;
    @Autowired
    private HourlyActivityAnalysisMapper hourlyActivityAnalysisMapper;

    @Value("${test.startDate:2025-06-14}")
    private String startDate;

    @Value("${test.endDate:2025-06-15}")
    private String endDate;

    // 获取每小时访问量数据（修改后）
    public List<Map<String, Object>> getHourlyVisits(String startDate, String endDate) {
        // 从数据库查询原始数据
        List<Map<String, Object>> originalData = hourlyActivityAnalysisMapper.getHourlyVisitsByRange(startDate, endDate);

        // 创建一个包含24小时的完整列表，默认访问量为1
        List<Map<String, Object>> result = new ArrayList<>();
        for (int hour = 0; hour < 24; hour++) {
            Map<String, Object> item = new HashMap<>();
            item.put("hour", hour);
            item.put("visitsCount", 1);  // 默认值为1
            result.add(item);
        }

        // 如果数据库中有实际数据，覆盖默认值（可选，这里仍设为1）
        if (originalData != null) {
            for (Map<String, Object> data : originalData) {
                Integer hour = (Integer) data.get("hour");
                if (hour != null && hour >= 0 && hour < 24) {
                    // 强制将访问量设为1，忽略数据库实际值
                    result.get(hour).put("visitsCount", 1);
                }
            }
        }

        return result;
    }

    // 硬编码的预期每小时访问量数据（模拟24小时数据）
//    private static final Map<Integer, Integer> EXPECTED_HOURLY_VISITS;
//
//    static {
//        Map<Integer, Integer> map = new HashMap<>();
//        // 示例数据：仅填充前4小时，实际需完整24小时
////        map.put(0, 164);
////        map.put(1, 172);
////        map.put(2, 50);
////        map.put(3, 46);
//        for (int i = 0; i < 24; i++) {
//            map.put(i, 60 + 2 * i);
//        }
//        // 省略4-23小时...
//        EXPECTED_HOURLY_VISITS = Collections.unmodifiableMap(map);
//    }
    @Override
    public StudentResult getJudgeIpResult(String ip) {
        StudentResult studentResult = new StudentResult();
        studentResult.setItemNumber("15");
        try {
            // 访问活跃时段分析接口
            String url = "http://" + ip + "/statistics/hourVisits";

            // 封装请求参数（日期范围）
            Map<String, String> params = new HashMap<>();
            params.put("startDate", startDate);
            params.put("endDate", endDate);

            String resultStr = httpUtil.doGet(url, null, params);
            studentResult.setResult(resultStr);

            studentResult.setResult(resultStr);

            // 验证返回结果
            JsonResult jsonResult = JSONObject.parseObject(resultStr, JsonResult.class);

            if (jsonResult.getCode() == 200) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                // 从数据库获取预期数据（修正方法调用）
                Map<Integer, Integer> expectedData = getExpectedHourlyDataFromDb(sdf.parse(startDate), sdf.parse(endDate));
                // 解析返回数据
                JSONArray dataArray = JSONObject.parseArray(jsonResult.getData().toString());
                List<Map> dataList = dataArray.toJavaList(Map.class);
                // 从数据库获取预期数据
                //Map<Integer, Integer> expectedData = getExpectedHourlyDataFromDb();

                if (validateHourlyData(dataList, expectedData)) {
                    studentResult.setScore(3.0);
                    studentResult.setComment("测试通过：返回24小时访问量数据正确");
                } else {
                    studentResult.setScore(0.0);
                    studentResult.setComment("返回数据格式或内容不符合要求");
                }
            } else {
                studentResult.setScore(0.0);
                studentResult.setComment("接口返回错误码：" + jsonResult.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            studentResult.setScore(0.0);
            studentResult.setResult(ErrorUtil.stackTraceToString(e));
            studentResult.setComment("执行测试时发生异常");
        }

        return studentResult;
    }

    /**
     * 从数据库获取预期的每小时访问量数据
     */
    private Map<Integer, Integer> getExpectedHourlyDataFromDb(Date startDate, Date endDate) {
        Map<Integer, Integer> expectedData = new HashMap<>();
        for (int i = 0; i < 24; i++) {
            expectedData.put(i, 0);
        }
        Calendar calendar = Calendar.getInstance();

        calendar.setTime(startDate);
        while (calendar.getTimeInMillis() < endDate.getTime()) {
            Date start = calendar.getTime();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            calendar.add(Calendar.HOUR_OF_DAY, 1);
            Date end = calendar.getTime();
            int count = hourlyActivityAnalysisMapper.countVisitByRange(start, end);
            expectedData.put(hour, expectedData.get(hour) + count);
        }
//        try {
//            // 获取两天的每小时数据（修正方法名）
//            List<Integer> hourlyDataDay1 = hourlyActivityAnalysisMapper.getHourlyVisitsByRange(this.startDate, this.endDate);
//            //List<Map<String, Object>> hourlyDataDay2 = hourlyActivityAnalysisMapper.getHourlyVisitsByRange(startDate2, endDate2);
//
//         System.out.println(hourlyDataDay1);
//            System.out.println("从数据库获取的预期每小时数据: " + expectedData);
//        } catch (Exception e) {
//            System.err.println("获取数据库数据失败: " + e.getMessage());
//            e.printStackTrace();
//        }

        return expectedData;
    }

    /**
     * 验证每小时访问量数据是否符合预期
     */
    private boolean validateHourlyData(List<Map> dataList, Map<Integer, Integer> expectedData) {
        // 检查数据条数是否为24小时
        if (dataList == null || dataList.size() != 24) {
            System.out.println("数据条数不正确，应为24条，实际: " + (dataList == null ? 0 : dataList.size()));
            return false;
        }

        // 验证每小时数据
        for (Map<String, Object> item : dataList) {
            Integer time = (Integer) item.get("time");
            Integer visitsCount = (Integer) item.get("visitsCount");

            if (time == null || visitsCount == null) {
                System.out.println("数据格式错误，time或visitsCount为空");
                return false;
            }

            // 检查小时范围是否在0-23之间
            if (time < 0 || time > 23) {
                System.out.println("小时超出范围: " + time);
                return false;
            }
            //TODO 验证数据需从数据库查询，不能使用默认数据，在判题过程中，数据可能会发生变化
            // 检查关键小时数据是否符合预期（示例仅验证前4小时）
            Integer expectedVisits = expectedData.get(time);
            if (expectedVisits == null || !visitsCount.equals(expectedVisits)) {
                System.out.println("小时 " + time + " 的访问量不匹配。预期: " + expectedVisits + ", 实际: " + visitsCount);
                return false;
            }
        }
        return true;
    }
}
